package com.xmy.cultivate.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.RecordCourseStudent;
import com.xmy.cultivate.entity.views.StudentClassLogRep;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.RecordCourseMapper;
import com.xmy.cultivate.respons.ClassesNum;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.record.Record;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记止课 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-08-10
 */
@RestController
@RequestMapping("/api/recordCourse")
@Scope("prototype")
public class RecordCourseController extends BaseController {

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    IRepairCourseService iRepairCourseService;

    @Autowired
    @Lazy
    IStudentService studentService;

    @Autowired
    @Lazy
    ICourseTypeService iCourseTypeService;
    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    IRecordBackDateSetService iRecordBackDateSetService;

    /**
     * 记上课列表
     *
     * @param reMap
     * @return
     */
    @GetMapping("classList")
    public Result recordClass(@RequestParam Map<String, Object> reMap,
                              @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType) {

        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<RecordCourse> iPage = new Page<>(pageNum, pageSize);


        String school_id = (String) reMap.get("schoolId");
        String teacher_id = (String) reMap.get("teacherId");
        String start_date = (String) reMap.get("startDate");
        String end_date = (String) reMap.get("endDate");
        String type = (String) reMap.get("type");//1：今日记上课，0：补记上课
        String status = (String) reMap.get("status");
        String subjectsId = (String) reMap.get("subjectsId");

        QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(school_id)) {
            queryWrapper.eq(StringUtils.isNotBlank(school_id), "school_id", school_id);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(teacher_id), "teacher_id", teacher_id);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);

        /**
         * 补记上课
         */
        LocalDate nowDate = DateUtil.getNowDate();
        if (StringUtils.isNotBlank(type) && type.equals("0")) {
            //queryWrapper.eq("status",type);

            if (StringUtils.isBlank(start_date) && StringUtils.isBlank(end_date)) {
                queryWrapper.eq("school_date", nowDate);
            } else {
                queryWrapper.between("school_date", start_date, end_date);
            }
        } else {
            queryWrapper.eq("school_date", nowDate);
        }

        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq("status", status);
        } else {
            //queryWrapper.eq("status",0);
        }
        queryWrapper.eq("deleted", 0);
        if (this.sourseLeve.equals(2)) {
            queryWrapper.eq("teacher_id", this.adminId);
        }


        iCourseSchedulingDetailService.findAllForPage(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    //记上课详细
    @GetMapping("/recordDetail/{id}")
    public Result getRecordOne(@PathVariable(value = "id") Long id) {
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneById(id);
        return new Result(Code.OK, courseSchedulingDetail);
    }

    //记上课详细学生列表
    @GetMapping("/recordStudents/{id}")
    public Result getRecordStudents(@PathVariable(value = "id") Long id) {
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(id);

        Map<String, Object> map = new HashMap<>();
        map.put("gradeId", courseSchedulingDetail.getGradeId());
        map.put("schedulingDetailId", courseSchedulingDetail.getId());

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", "select student_id from student_grade where status<>3 and reading_status=1 and deleted=0 and  grade_id = " + courseSchedulingDetail.getGradeId());
        //排除已记上课的学员
        queryWrapper.notInSql("id", "select student_id from record_course where is_deduct_house =1 and deleted=0 and scheduling_detail_id = " + courseSchedulingDetail.getId());

        //临时学员
        //queryWrapper.or();
        //queryWrapper.inSql("id","select student_id from student_grade_temporary where grade_id = "+courseSchedulingDetail.getGradeId()+" and scheduling_detail_id="+courseSchedulingDetail.getId());

        List<RecordCourseStudent> mapList = iCourseSchedulingDetailService.recordStudentList(queryWrapper, courseSchedulingDetail.getId(), courseSchedulingDetail.getGradeId(), courseSchedulingDetail.getCourseId(), courseSchedulingDetail.getSchoolId());
        return new Result(Code.OK, mapList);
    }

    /**
     * 保存记上课
     *
     * @param courseSchedulingDetail
     * @return
     */
    @PostMapping("/recordAction")
    public Result RecordAction(@RequestBody CourseSchedulingDetail courseSchedulingDetail) {
        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());
        if (courseSchedulingDetailInfo == null) {
            throw new CommonException(ResultCode.CourseScheduling);
        }

        Iterator<RecordCourse> recordCourseIterator = courseSchedulingDetail.getRecordCourseList().iterator();
        while (recordCourseIterator.hasNext()) {
            RecordCourse recordCourse = recordCourseIterator.next();
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getBuckleClassHouse() > 0) {
                QueryWrapper<LackCourseLog> lackCourseLogQueryWrapper = new QueryWrapper<>();
                lackCourseLogQueryWrapper.eq("year_part", courseSchedulingDetailInfo.getYearPart());
                lackCourseLogQueryWrapper.eq("quarter_num", courseSchedulingDetailInfo.getQuarter());
                lackCourseLogQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                lackCourseLogQueryWrapper.eq("student_id", recordCourse.getStudentId());
                lackCourseLogQueryWrapper.eq("lesson_num", courseSchedulingDetailInfo.getLessonNum());
                lackCourseLogQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                lackCourseLogQueryWrapper.last("limit 1");
                LackCourseLog lackCourseLog = iLackCourseLogService.getOne(lackCourseLogQueryWrapper);
                if (lackCourseLog != null && (lackCourseLog.getIsSignIn().equals(1) || lackCourseLog.getIsRepair().equals(1))) {
                    Student student = studentService.getById(recordCourse.getStudentId());
                    return new Result(Code.ERROR, "", student.getName() + "当前课次已经添加了缺课并且已经签到补课，不能再扣课时");
                }
            }
        }
        boolean rs = iRecordCourseService.batchAdd(courseSchedulingDetail);
        return new Result(Code.OK);
    }

    @GetMapping("/recordGradeLog")
    @ApiOperation("按班级获取记录")
    public Result recordGradeLog(
            @RequestParam(value = "pageNum", defaultValue = "1") String pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") String pageSize,
            @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
            @RequestParam(value = "courseId", defaultValue = "") String courseId,
            @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
            @RequestParam(value = "status", defaultValue = "") String status,
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
            @RequestParam(value = "lessonNum", defaultValue = "", required = false) String lessonNum,
            @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
            @RequestParam(value = "startDate", defaultValue = "") String startDate,
            @RequestParam(value = "endDate", defaultValue = "") String endDate) {

        IPage<RecordCourse> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        QueryWrapper queryWrapper = new QueryWrapper();
        Quarter quarterInfo = iQuarterService.getNowQuarter();
        queryWrapper.eq("t1.year_part", quarterInfo.getYearPart());
        queryWrapper.eq("t1.quarter", quarterInfo.getNum());
        queryWrapper.eq("t1.deleted", 0);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "t1.grade_id", gradeId);
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "t1.school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "t1.teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "t1.subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "t1.course_id", courseId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonNum), "t1.lesson_num", lessonNum);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "t2.year_class_id", yearClassId);
        queryWrapper.orderByAsc("t1.school_date");
        if ((StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate))) {
            queryWrapper.between("t1.school_date", startDate, endDate);
            queryWrapper.orderByAsc("t1.school_date", startDate, endDate);
        }
        if (this.sourseLeve.equals(2)) {
            queryWrapper.eq("t1.teacher_id", this.adminId);
        }

        iRecordCourseService.recordGradeLog(page, queryWrapper);
        return new Result(Code.OK, new PageResult<>(page.getRecords(), page.getTotal(), page.getPages()), "");
    }

    /**
     * 上课记录
     *
     * @return
     */
    @GetMapping("/studentClassLog")
    public Result studentClassLog(@RequestParam(value = "pageNum", defaultValue = "1") String pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") String pageSize,
                                  @RequestParam(value = "gradeId", defaultValue = "") String gradeId,
                                  @RequestParam(value = "courseId", defaultValue = "") String courseId,
                                  @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                                  @RequestParam(value = "status", defaultValue = "") String status,
                                  @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                                  @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
                                  @RequestParam(value = "startDate", defaultValue = "") String startDate,
                                  @RequestParam(value = "endDate", defaultValue = "") String endDate,
                                  @RequestParam(value = "studentName", defaultValue = "") String studentName,
                                  @RequestParam(value = "logType", defaultValue = "") String logType,
                                  @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId,
                                  @RequestParam(value = "repairType") List<String> repairTypeArr,
                                  @RequestParam(value = "repairDate", defaultValue = "") String repairDate,
                                  @RequestParam(value = "backDate", defaultValue = "") String backDate,
                                  @RequestParam(value = "courseType", defaultValue = "") String courseType,
                                  @RequestParam(value = "lessonNum", defaultValue = "") String lessonNum,
                                  @RequestParam(value = "yearPart", defaultValue = "", required = false) String yearPart,
                                  @RequestParam(value = "quarterNum", defaultValue = "", required = false) String quarterNum,
                                  @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType,
                                  @RequestParam(value = "courseTypeId", defaultValue = "", required = false) String courseTypeId) {

        IPage<RecordCourse> iPage = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        QueryWrapper<StudentClassLogRep> queryWrapper = new QueryWrapper<>();

        Quarter quarterInfo = iQuarterService.getNowQuarter();

        //queryWrapper.eq("year_part",quarterInfo.getYearPart());
        //queryWrapper.eq("quarter",quarterInfo.getNum());
        queryWrapper.eq("deleted", 0);


        if (StringUtils.isNotBlank(schoolId)) {
            queryWrapper.inSql("school_id", schoolId);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }

        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);

        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq(StringUtils.isNotBlank(courseType), "course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        queryWrapper.eq(StringUtils.isNotBlank(lessonNum), "lesson_num", lessonNum);
        queryWrapper.inSql(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);


        //type等于1正常上课的学生
        //queryWrapper.eq(StringUtils.isNotBlank(subjectsId),"type",1);
        //logType 0上课记录,1补课管理
        if (StringUtils.isNotBlank(logType) && logType.equals("1")) {
            //补课管理
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                queryWrapper.between("school_date", startDate, endDate);
            } else if (StringUtils.isNotBlank(startDate)) {
                queryWrapper.eq("school_date", startDate);
            } else if (StringUtils.isNotBlank(endDate)) {
                queryWrapper.eq("school_date", endDate);
            }
            queryWrapper.eq("status", 2);
            queryWrapper.ne("deduct_type", 4);//扣课时方式，0未知，1自动，2是手动，3满15次后按消课扣课时,4请假超过两次扣除
            queryWrapper.eq(StringUtils.isNotBlank(courseTypeId), "course_type_id ", courseTypeId);
            queryWrapper.ne("is_deduct_house", 3);

            if (repairTypeArr.size() > 0) {
                Collections.sort(repairTypeArr);
                String sql = "(";
                //0未安排，1，已补课，2已安排，3未补已扣
                // 后台的未安排+已安排=未补未扣，后台补课类型增加：未补已扣（10月24）
                for (String repairType : repairTypeArr) {
                    //未安排
                    if (repairType.equals("0")) {
                        //未安排的is_repair为0或者is_repair为2并且结束时间小于等于当前时间
                        sql += "(is_repair=" + repairType + " AND buckle_class_money = 0 or (is_repair=2 AND buckle_class_money = 0 and repair_end_date_time<='" + LocalDateTime.now().withNano(0) + "'))";
                        //queryWrapper.and(i->i.eq("is_repair",repairType).or(j->j.eq("is_repair",2).le("repair_end_date_time",LocalDateTime.now().withNano(0))));
                    } else if (repairType.equals("1")) {
                        if (repairTypeArr.contains("0")) {
                            sql += "or";
                        }
                        sql += "(is_repair = 1)";
                        //queryWrapper.eq("is_repair",repairType);
                    } else if (repairType.equals("2")) {
                        if (repairTypeArr.contains("0") || repairTypeArr.contains("1")) {
                            sql += "or";
                        }
                        sql += " (is_repair=2 AND buckle_class_money = 0 and repair_end_date_time>='" + LocalDateTime.now().withNano(0) + "')";
                        //queryWrapper.eq("is_repair",repairType);
                        //queryWrapper.ge("repair_end_date_time",LocalDateTime.now().withNano(0));
                    } else if (repairType.equals("3")) {// 未补已扣
                        if (repairTypeArr.contains("0") || repairTypeArr.contains("1") || repairTypeArr.contains("2")) {
                            sql += "or";
                        }
                        sql += "(is_repair <> 1 AND is_deduct_house = 1 AND is_deduct_money = 1 AND buckle_class_house > 0 )";
                    }
                }
                sql += ")";
                queryWrapper.apply(sql);
            }
            if (StringUtils.isNotBlank(repairDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MAX);
                queryWrapper.between("repair_end_date_time", startDateTime, endDateTime);
            }
            if (StringUtils.isNotBlank(backDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(backDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(backDate), LocalTime.MAX);
                queryWrapper.between("back_date", startDateTime, endDateTime);
            }
            //queryWrapper.orderByDesc("school_date");
        } else {
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                queryWrapper.between("school_date", startDate, endDate);
            }
            /*if (StringUtils.isNotBlank(repairDate)) {
                LocalDateTime startDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MIN);
                LocalDateTime endDateTime = LocalDateTime.of(LocalDate.parse(repairDate), LocalTime.MAX);
                queryWrapper.between("repair_end_date_time",startDateTime,endDateTime);
            }*/
            if (status.equals("1")) {
                queryWrapper.eq("status", 1);
            } else if (status.equals("2")) {
                queryWrapper.eq("status", 2);
                queryWrapper.ne("is_repair", 1);
            } else if (status.equals("3")) {
                queryWrapper.eq("status", 3);
                queryWrapper.ne("is_repair", 1);
            } else if (status.equals("100")) {//请假已补
                queryWrapper.eq(StringUtils.isNotBlank(status), "status", 2);
                queryWrapper.eq("is_repair", 1);
            } else if (status.equals("101")) {//请假已扣
                queryWrapper.eq(StringUtils.isNotBlank(status), "status", 2);
                queryWrapper.eq("is_deduct_house", 1);
                queryWrapper.eq("is_deduct_money", 1);
                queryWrapper.gt("buckle_class_house", 0);
            }

            //queryWrapper.orderByAsc("school_date");
        }

        if (StringUtils.isNotBlank(studentName)) {
            //queryWrapper.inSql("student_id","select id from student where name like '%"+studentName+"%'");
            queryWrapper.eq("student_name", studentName);
        }

        if (this.sourseLeve.equals(2)) {
            queryWrapper.and(i -> i.eq("old_teacher_id", this.adminId).or().eq("teacher_id", this.adminId));
        }

        List<String> orderBy = new ArrayList<>();
        orderBy.add("school_date");
        orderBy.add("id");
        queryWrapper.orderByDesc(orderBy);

        iRecordCourseService.studentClassLog(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));

    }

    /**
     * 切换上课记录状态
     *
     * @return
     */
    @PutMapping("/checkRecordStatus")
    public Result checkRecordStatus(@RequestBody RecordCourse recordCourse) {
        RecordCourse recordCourseInfo = iRecordCourseService.getById(recordCourse.getId());
        if (recordCourseInfo == null) {
            return new Result(Code.ERROR, "", "数据不存在");
        }

        /**
         * 如果已经按排补课，不能修改状态
         */
        if (recordCourseInfo.getIsRepair().equals(1)) {
            return new Result(Code.ERROR, "", "已补课，不能修改");
        }

        //由请假改为到课
        if (!recordCourseInfo.getIsDeductMoney().equals(0) && recordCourseInfo.getUseLeaveNum() > 0 && recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
            //return new Result(Code.ERROR,"","请假次超过大于等于2，不能改为到课");
        }


        if (!recordCourseInfo.getCourseType().equals(1)) {
            //return new Result(Code.ERROR,"","正常排课的才能修改状态");
        }

        if (recordCourseInfo.getIsRepair().equals(2) && recordCourseInfo.getRepairEndDateTime().isAfter(LocalDateTime.now().withNano(0))) {
            return new Result(Code.ERROR, "", "已安排补课，不能修改");
        }

        //是否已经补课
        if (recordCourseInfo.getRepairId() != null) {
            RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getRepairId());
            if (repairCourse != null) {
                //是否已经补课
                if (repairCourse.getIsSignIn().equals(1)) {
                    RecordCourse recordCourseNew = iRecordCourseService.getOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                    if (recordCourseNew != null) {
                        return new Result(Code.ERROR, "", "安排补课已到课，不能修改");
                    }
                }
            }
        }


        /*if(recordCourseInfo.getStatus().getKey().equals(1)){
            recordCourseInfo.setStatus(StatusRecordEnum.LEAVE);
        }else {
            recordCourseInfo.setStatus(StatusRecordEnum.REACH);
        }*/

        if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourseInfo.getStatus().equals(StatusRecordEnum.LEAVE) && !recordCourseInfo.getIsDeductMoney().equals(0) && recordCourse.getStatus().getKey().equals(2)) {

        } else {
            if (recordCourseInfo.getStatus().equals(recordCourse.getStatus())) {
                return new Result(Code.OK, "", "成功");
            }
        }


        /**
         * 到课
         */
        boolean rs = true;
        if (recordCourseInfo.getStatus().equals(StatusRecordEnum.Truancy) && recordCourse.getStatus().getKey().equals(1)) {
            //旷课调整为到课
            recordCourseInfo.setStatus(StatusRecordEnum.REACH);
            recordCourseInfo.setUseLeaveNum(0);
            iRecordCourseService.updateById(recordCourseInfo);
            return new Result(Code.OK, "", "成功");
        } else if (recordCourseInfo.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourse.getStatus().getKey().equals(1)) {
            //请假调整为到课
            rs = iRecordCourseService.recordCourseChangeArrice(recordCourse.getId(), StatusRecordEnum.REACH, ReachTypeEnum.LATE);
        } else if ((recordCourseInfo.getStatus().equals(StatusRecordEnum.REACH) || recordCourseInfo.getStatus().equals(StatusRecordEnum.Truancy)) && recordCourse.getStatus().getKey().equals(2)) {
            rs = iRecordCourseService.recordCourseChangeLive(recordCourse.getId());
        } else if (recordCourseInfo.getStatus().equals(StatusRecordEnum.LEAVE) && recordCourse.getStatus().getKey().equals(3)) {
            //由请假改为旷课
            rs = iRecordCourseService.recordCourseChangeArrice(recordCourse.getId(), StatusRecordEnum.Truancy, ReachTypeEnum.LATE);
        } else if (recordCourseInfo.getStatus().equals(StatusRecordEnum.LEAVE) && !recordCourseInfo.getIsDeductMoney().equals(0) && recordCourse.getStatus().getKey().equals(2)) {
            // 由请假已扣改为请假未扣
            rs = iRecordCourseService.updateSendBackLeave(recordCourse.getId());
        }
        //recordCourseInfo.setStatus(recordCourse.getStatus());
        //iRecordCourseService.updateById(recordCourseInfo);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }

    /**
     * 手动消课(满15次后)
     *
     * @param recordCourseParam
     * @return
     */
    @PostMapping("/recordActionConsume")
    public Result recordActionConsume(@RequestBody RecordCourse recordCourseParam) {
        RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());
        if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
            return new Result(Code.ERROR, "", "该记上课不能做消课操作");
        }
        return iRecordCourseService.recordActionConsume(recordCourse);
    }

    /**
     * 取消手动消课
     *
     * @param recordCourseParam
     * @return
     */
    @PostMapping("/resetRecordConsume")
    public Result resetRecordConsume(@RequestBody RecordCourse recordCourseParam) {
        RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());
        if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH) || !recordCourse.getIsDeductHouse().equals(1) || !recordCourse.getDeductType().equals(3)) {
            return new Result(Code.ERROR, "", "该记上课不能做取消消课操作");
        }
        iRecordCourseService.resetRecordConsume(recordCourse);
        return new Result(Code.OK, "", "操作成功");
    }


    /**
     * 补课到课
     *
     * @param recordCourse
     * @return
     */
    @PutMapping("/repairArrive")
    public Result repairArrive(@RequestBody RecordCourse recordCourse) {
        Long recordCourseId = recordCourse.getId();
        //缺课记上课记录
        RecordCourse recordCourseOld = iRecordCourseService.getById(recordCourseId);
        if (recordCourseOld.getIsRepair().equals(1)) {
            return new Result(Code.ERROR, "", "已补课，不要重复操作");
        }
        boolean rs = iRecordCourseService.leaveArrive(recordCourseId);

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }

    /**
     * 扣课时或者金额
     *
     * @param recordCourse
     * @return
     */
    @PostMapping("/buckleHouseOrMoney")
    @RepeatSubmit(expireSeconds = 5)
    public Result buckleHouseOrMoney(@RequestBody RecordCourse recordCourse) {
        Long recordCourseId = recordCourse.getId();
        RecordCourse recordCourseOld = iRecordCourseService.getById(recordCourseId);
        if (recordCourseOld.getIsDeductHouse().equals(1) && recordCourseOld.getIsDeductMoney().equals(1)) {
            return new Result(Code.ERROR, "", "已扣课时与金额，不要重复操作");
        }
        if (recordCourseOld.getIsDeductHouse().equals(3) && recordCourseOld.getIsDeductMoney().equals(3)) {
            return new Result(Code.ERROR, "", "已扣满15课次，不能再扣课时");
        }
        if (!recordCourseOld.getStatus().equals(StatusRecordEnum.REACH)) {
            return new Result(Code.ERROR, "", "到课的才能操作");
        }
        boolean rs = false;
        if (recordCourseOld.getCourseType().equals(1)) {
            rs = iRecordCourseService.recordAction(recordCourseOld);
        } else if (recordCourseOld.getCourseType().equals(3)) {
            rs = iRecordCourseService.repairBuckleMoney(recordCourseOld.getSchedulingDetailId());
        } else if (recordCourseOld.getCourseType().equals(4)) {
            QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
            repairCourseQueryWrapper.eq("id", recordCourseOld.getSchedulingDetailId());
            Long count = iRepairCourseService.count(repairCourseQueryWrapper);
            if (count > 0) {
                rs = iRecordCourseService.recordActionRepair(recordCourseOld);//按单学员调课
            } else {
                rs = iRecordCourseService.recordAction(recordCourseOld);//按班级调课
            }
        } else if (recordCourseOld.getCourseType().equals(5)) {
            rs = iRecordCourseService.recordActionRepair(recordCourseOld);
        } else if (recordCourseOld.getCourseType().equals(6)) {
            rs = iRecordCourseService.recordActionRepair(recordCourseOld);
        } else if (recordCourseOld.getCourseType().equals(9)) {
            rs = iRecordCourseService.recordActionRepair(recordCourseOld);
        }
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }

    /**
     * 试听课，课时核对时，扣课时
     *
     * @param recordCourse
     * @return
     */
    @PostMapping("/tryListenBuckleHouse")
    @RepeatSubmit(expireSeconds = 5)
    public Result tryListenBuckleHouse(@RequestBody RecordCourse recordCourse) {
        Long recordCourseId = recordCourse.getId();
        RecordCourse recordCourseOld = iRecordCourseService.getById(recordCourseId);
        if (recordCourseOld.getIsDeductHouse().equals(1) && recordCourseOld.getIsDeductMoney().equals(1)) {
            return new Result(Code.ERROR, "", "已扣课时与金额，不要重复操作");
        }
        recordCourseOld.setCreatedId(recordCourse.getCreatedId());//调整为核对人
        Result rs = iRecordCourseService.tryListenBuckleHouse(recordCourseOld);
        return rs;
    }


    /**
     * 缺课到课
     */
    @PutMapping("/lackRepairArrive")
    public Result lackRepairArrive(@RequestBody LackCourseLog lackCourseLog) {
        Long lackCourseLogId = lackCourseLog.getId();
        //缺课记上课记录
        LackCourseLog lackCourseLogOld = iLackCourseLogService.getById(lackCourseLogId);
        if (lackCourseLogOld.getIsRepair().equals(1)) {
            return new Result(Code.ERROR, "", "已补课，不要重复操作");
        }
        boolean rs = iRecordCourseService.lackRepairArrive(lackCourseLogId);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }


    /**
     * 消课扣课时，此接口作废
     *
     * @param recordCourse
     * @return
     */
    @PutMapping("/moreRecordeCourse")
    public Result moreRecordeCourse(@RequestBody RecordCourse recordCourse) {
        Long recordCourseId = recordCourse.getId();
        boolean rs = iRecordCourseService.moreRecordeCourse(recordCourseId);
        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "成功" : "失败");
    }


    /**
     * 删除记上课
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {

        RecordCourse recordCourseInfo = iRecordCourseService.getById(id);
        if (recordCourseInfo == null) {
            return new Result(Code.ERROR, "", "数据不存在");
        }

        /**
         * 如果已经按排补课，不能修改状态
         */
        if (recordCourseInfo.getIsRepair().equals(1)) {
            return new Result(Code.ERROR, "", "已补课，不能删除");
        }

        if (recordCourseInfo.getIsRepair().equals(2) && recordCourseInfo.getRepairEndDateTime().isAfter(LocalDateTime.now().withNano(0))) {
            return new Result(Code.ERROR, "", "已安排补课，不能删除");
        }

        boolean rs = iRecordCourseService.deleteForId(id);
        if (rs) {
            try {
                //iStudentGradeService.updateIsPresort(recordCourseInfo.getSchoolId(),recordCourseInfo.getStudentId(),recordCourseInfo.getYearPart(),recordCourseInfo.getQuarter(),recordCourseInfo.getSubjectsId(),recordCourseInfo.getLessonType());
                iMqPushService.updateIsPresortForRecord(recordCourseInfo.getSchoolId(), recordCourseInfo.getStudentId(), recordCourseInfo.getYearPart(), recordCourseInfo.getQuarter(), recordCourseInfo.getSubjectsId(), recordCourseInfo.getLessonType());
            } catch (Exception e) {
            }
        }

        return new Result(rs ? Code.OK : Code.ERROR, "", rs ? "删除成功" : "删除失败");

    }

    @GetMapping("HourStatistics")
    public Result HourStatistics(@RequestBody Map reMap, @RequestParam(value = "pageNum", defaultValue = "1") String pageNum, @RequestParam(value = "pageSize", defaultValue = "10") String pageSize) {
        IPage<RecordCourse> ipage = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        String schoolId = (String) reMap.get("schoolId");
        String subjectId = (String) reMap.get("subjectId");
        String timeStart = (String) reMap.get("timeStart");
        String timeEnd = (String) reMap.get("timeEnd");
        String teacherId = (String) reMap.get("teacherId");
        String courseId = (String) reMap.get("courseId");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectId), "subject_id", subjectId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.between(StringUtils.isNotBlank(timeStart) && StringUtils.isNotBlank(timeEnd), "school_date", timeStart, timeEnd);
        queryWrapper.groupBy("teacher_id");
        queryWrapper.orderByAsc("teacher_id");
        iRecordCourseService.hourStatistics(ipage, queryWrapper);
        return new Result(Code.OK, ipage, "");
    }

    @GetMapping("HourStudentStatistics")
    public Result HourStudentStatistics(@RequestBody Map reMap, @RequestParam(value = "pageNum", defaultValue = "1") String pageNum, @RequestParam(value = "pageSize", defaultValue = "10") String pageSize) {
        IPage<RecordCourse> ipage = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        String schoolId = (String) reMap.get("schoolId");
        String subjectId = (String) reMap.get("subjectId");
        String timeStart = (String) reMap.get("timeStart");
        String timeEnd = (String) reMap.get("timeEnd");
        String teacherId = (String) reMap.get("teacherId");
        String courseId = (String) reMap.get("courseId");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(subjectId), "subject_id", subjectId);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        queryWrapper.eq(StringUtils.isNotBlank(courseId), "course_id", courseId);
        queryWrapper.between(StringUtils.isNotBlank(timeStart) && StringUtils.isNotBlank(timeEnd), "school_date", timeStart, timeEnd);
        queryWrapper.groupBy("student_id");
        queryWrapper.orderByAsc("student_id");
        iRecordCourseService.hourStudentStatistics(ipage, queryWrapper);
        return new Result(Code.OK, ipage, "");
    }

    /**
     * 修改上课老师
     *
     * @return
     */
    @PostMapping("/updateClassTeahcer")
    public Result updateClassTeahcer(@RequestBody RecordCourse recordCourseParam) {
        RecordCourse recordCourse = iRecordCourseService.getById(recordCourseParam.getId());
        Staff staff = iStaffService.getById(recordCourseParam.getTeacherId());
        if (staff == null) {
            return new Result(Code.ERROR, "", "老师不存在");
        }
        recordCourse.setTeacherId(staff.getId());
        recordCourse.setTeacherName(staff.getName());
        iRecordCourseService.updateById(recordCourse);
        return new Result(Code.OK, "", "修改成功");
    }

    @GetMapping("/getLeaveRecord")
    public Result getLeaveRecord(@RequestParam Map reMap,
                                 @RequestParam("subjectsId") String subjectsId) {
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String studentId = (String) reMap.get("studentId");

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("status", 2);
        wrapper.eq("lesson_type", 1);
        wrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        wrapper.ne("is_repair", 1);
        wrapper.eq("deleted", 0);
        wrapper.eq("student_id", studentId);
        wrapper.eq("quarter", quarterNum);
        wrapper.eq("year_part", yearPart);
        wrapper.ne("deduct_type", 4);//4请假超过两次扣除课时
        List<RecordCourse> recordCourseList = iRecordCourseService.list(wrapper);
        return new Result(Code.GET_OK, recordCourseList, Code.GET_OK_MSG);
    }

    /**
     * 删除请假记录
     *
     * @param reMap
     * @return
     */
    @PostMapping("/delLeaveRecord")
    public Result delLeaveRecord(@RequestBody Map reMap) {
        String ids = (String) reMap.get("ids");
        //iRecordCourseService.delLeaveRecord(ids);
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            iRecordCourseService.deleteForId(Long.parseLong(id));
        }
        return new Result(Code.DELETE_OK, "", Code.DELETE_OK_MSG);
    }

    /**
     * 课时汇总列表
     */
    @GetMapping("/classesNumTotal")
    public Result classesNumTotal(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<ClassesNum> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String teacherId = (String) reMap.get("teacherId");
        String type = (String) reMap.get("type");//1个人 2校区老师 3校长 4校区
        String isDescOrAsc = (String) reMap.get("isDescOrAsc");//0正序 1倒序
        if (StringUtils.isBlank(isDescOrAsc)) {
            isDescOrAsc = "1";
        }
        String isFieldToSc = (String) reMap.get("isFieldToSc");// 要排序的字段，已上课次：buckleClassHouse，课时费：buckleClassMoney
        if (StringUtils.isBlank(isFieldToSc)) {
            isFieldToSc = "buckleClassHouse";
        }

        iRecordCourseService.classesNumList(iPage, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId, type, isDescOrAsc, isFieldToSc);

        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 课时汇总详情
     */
    @GetMapping("/classesNumDetails")
    public Result classesNumDetails(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<ClassesNum> iPage = new Page<>(pageNum, pageSize);

        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String schoolId = (String) reMap.get("schoolId");
        String subjectsId = (String) reMap.get("subjectsId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String teacherId = (String) reMap.get("teacherId");

        iRecordCourseService.classesNumDetails(iPage, yearPart, quarterNum, schoolId, subjectsId, startDate, endDate, teacherId);

        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 调整迟到状态
     */
    @PostMapping("/updateReach")
    public Result updateReach(@RequestBody Map reMap) {
        Integer reachType = (Integer) reMap.get("reachType");// 1为准时，2迟到
        String id = (String) reMap.get("id");

        RecordCourse recordCourse = iRecordCourseService.getById(id);
        if (Objects.isNull(recordCourse)) {
            return new Result(Code.DELETE_OK, "", "该数据不存在");
        }

        iRecordCourseService.updateReach(reachType, Long.valueOf(id));

        return new Result(Code.DELETE_OK, "", Code.DELETE_OK_MSG);
    }

    /**
     * 延长超时禁补日期
     */
    @PostMapping("/updateRecordBackDate")
    public Result updateRecordBackDate(@RequestBody Map reMap) {
        List<Object> recordBackDateSetList = (List<Object>) reMap.get("recordBackDateSetList");

        StringBuilder msgSb = new StringBuilder();

        for (Object recordBackDate : recordBackDateSetList) {
            String jsonObject = JSON.toJSONString(recordBackDate);
            RecordBackDateSet recordBackDateSet = JSONObject.parseObject(jsonObject, RecordBackDateSet.class);

            RecordBackDateSet backDateSet = iRecordBackDateSetService.getOne(new QueryWrapper<RecordBackDateSet>().eq("record_course_id", recordBackDateSet.getRecordCourseId()));

            RecordCourse recordCourse = iRecordCourseService.getById(recordBackDateSet.getRecordCourseId());
            if (recordCourse != null) {
                if (recordBackDateSet.getBackDate().isBefore(recordCourse.getSchoolDate())) {
                    msgSb.append(recordCourse.getStudentName()).append(" 当前禁补日期不能小于原本上课日期").append(recordCourse.getSchoolDate()).append("；");
                    continue;
                }

                if (backDateSet == null) {
                    LocalDate schoolDate = recordCourse.getSchoolDate();

                    LocalDate backDate = schoolDate
                            .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                            .plusWeeks(2);

                    if (recordBackDateSet.getBackDate().isBefore(backDate)) {
                        msgSb.append(recordCourse.getStudentName()).append(" 当前禁补日期不能小于原本禁补日期").append(backDate).append("；");
                    }
                } else {
                    if (recordBackDateSet.getBackDate().isBefore(backDateSet.getBackDate())) {
                        msgSb.append(recordCourse.getStudentName()).append(" 当前禁补日期不能小于原本禁补日期").append(backDateSet.getBackDate()).append("；");
                    }
                }
            }
        }

        if (msgSb.length() > 0) {
            return new Result(Code.ERROR, "", msgSb.toString());
        }


        for (Object recordBackDate : recordBackDateSetList) {
            String jsonObject = JSON.toJSONString(recordBackDate);
            RecordBackDateSet recordBackDateSet = JSONObject.parseObject(jsonObject, RecordBackDateSet.class);

            RecordBackDateSet backDateSet = iRecordBackDateSetService.getOne(new QueryWrapper<RecordBackDateSet>().eq("record_course_id", recordBackDateSet.getRecordCourseId()));

            if (backDateSet == null) {
                backDateSet = new RecordBackDateSet();
                backDateSet.setRecordCourseId(recordBackDateSet.getRecordCourseId());
                backDateSet.setBackDate(recordBackDateSet.getBackDate());
                iRecordBackDateSetService.save(backDateSet);
            } else {
                backDateSet.setBackDate(recordBackDateSet.getBackDate());
                iRecordBackDateSetService.updateById(backDateSet);
            }
        }

        return new Result(Code.OK, "", Code.OK_MSG);
    }

}
